package it.polimi.travelDream.ejb.servlet;

import it.polimi.travelDream.ejb.interfaces.HotelMgrRemote;

import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Map;

import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class TravelServlet
 */
@WebServlet("/AddHotel")
public class AddHotel extends HttpServlet {
	private static final long serialVersionUID = 1L;
	DateFormat format = new SimpleDateFormat("dd/MM/yyyy");
	@EJB
	HotelMgrRemote umr;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public AddHotel() {
		super();
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Map<String, String[]> mappa = request.getParameterMap();
		format.setLenient(false);
		/*Empty Fields Check*/
		if (mappa.get("name")[0].isEmpty() || mappa.get("address")[0].isEmpty() || mappa.get("city")[0].isEmpty() || mappa.get("availability")[0].isEmpty() || mappa.get("typeRum")[0].isEmpty() ||	mappa.get("costPerDay")[0].isEmpty())
		{
			request.setAttribute("message","Empty fields.");
			request.getRequestDispatcher("/BPAddHotel.jsp").forward(request, response); 
		}
		else 
		{
			 try {
				 Integer.parseInt(mappa.get("costPerDay")[0]);
				 format.parse(mappa.get("availability")[0]);
				 /*Hotel Insertion*/
					umr.addHotel(mappa.get("name")[0], mappa.get("address")[0], mappa.get("city")[0],mappa.get("availability")[0], mappa.get("typeRum")[0],mappa.get("costPerDay")[0]);
					/*Next JSP parameters and call */
					request.setAttribute("message", "Hotel " +mappa.get("name")[0] +" succesfully added.");
					request.getRequestDispatcher("/BPAdvice.jsp").forward(request, response); 
				 
				 } catch (ParseException e) {
				 
					 request.setAttribute("message","date must be in  dd/MM/yyyy format and availability must be an integer");
						request.getRequestDispatcher("/BPAddHotel.jsp").forward(request, response); 
					 
				 }
			 
			
			
		}
	}

}
